package org.example.journal_items.UserDao;

import org.example.journal_items.Entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

// MyBatis Mapper接口
@Mapper
public interface UserDao {// UserDao.java
        // 按用户名查询完整用户对象
        @Select("SELECT id, username, password, avatar, tags, birthday, bio, nickname, theme, created_at as createdAt, updated_at as updatedAt, is_first_login as isFirstLogin FROM users WHERE username = #{username}")
        @org.apache.ibatis.annotations.Results({
                        @org.apache.ibatis.annotations.Result(property = "tags", column = "tags", typeHandler = org.example.journal_items.common.JsonListTypeHandler.class)
        })
        User findByUsername(@Param("username") String username);

        // 保持原有的方法用于直接验证
        @Select("SELECT password FROM users WHERE username = #{username} AND password = #{password}")
        String findByAccountAndPassword(@Param("username") String username, @Param("password") String password);

        // 新增用户
        @Insert("INSERT INTO users(username, password, avatar, tags, birthday, bio, nickname, created_at, updated_at, is_first_login) VALUES(#{username}, #{password}, #{avatar}, #{tags, typeHandler=org.example.journal_items.common.JsonListTypeHandler}, #{birthday}, #{bio}, #{nickname}, NOW(), NOW(), #{isFirstLogin})")
        void insertUser(User user);

        // 按ID查询用户
        @Select("SELECT id, username, password, avatar, tags, birthday, bio, nickname, theme, created_at as createdAt, updated_at as updatedAt, is_first_login as isFirstLogin FROM users WHERE id = #{id}")
        @org.apache.ibatis.annotations.Results({
                        @org.apache.ibatis.annotations.Result(property = "tags", column = "tags", typeHandler = org.example.journal_items.common.JsonListTypeHandler.class)
        })
        User findById(@Param("id") Long id);

        // 更新用户头像
        @Update("UPDATE users SET avatar = #{avatar}, updated_at = NOW() WHERE id = #{id}")
        void updateAvatar(@Param("id") Long id, @Param("avatar") String avatar);

        @Update("UPDATE users SET username = #{username}, avatar = #{avatar}, tags = #{tags, typeHandler=org.example.journal_items.common.JsonListTypeHandler}, birthday = #{birthday}, bio = #{bio}, nickname = #{nickname}, is_first_login = #{isFirstLogin}, updated_at = NOW() WHERE id = #{id}")
        void updateUserInfo(User user);

        // 更新用户主题
        @Update("UPDATE users SET theme = #{theme}, updated_at = NOW() WHERE id = #{id}")
        void updateUserTheme(@Param("id") Long id, @Param("theme") String theme);
}
